import React, { useRef, useEffect, useState } from 'react'
import moment from 'moment'
import { message } from 'antd'
import style from './Index.module.less'
import CaseTypeBlock from './components/CaseTypeBlock'
import SearchForm from '@components/SearchForm/Index'
import { awaitWrap } from '@js/tool'
import { getTotal } from './ajax/index'

function getThisYear () {
  const year = moment().year()
  const begin = moment(`${year}-01-01 00:00:00`)
  const end = moment(begin)
  end.add(1, 'y')
  end.subtract(1, 's')
  return {
    beginTime: begin,
    endTime: end
  }
}

// 格式化条件
function formatCondition (condition, formData, setCondition, setFormData) {
  condition.push({ k: 'casetype', o: '=', v: '金融案件' })
  setCondition(condition)
  setFormData(formData)
}

// 转换单位
function transferUnit (v) {
  if (v > 100000000) {
    return Math.round(v / 1000000) / 100 + ' 亿'
  }
  if (v > 10000) {
    return Math.round(v / 100) / 100 + ' 万'
  }
  return v
}

// 初试化全部统计数据
async function initTotal (condition, setLoading, setCasenum, setDisputeamount) {
  if (!condition) {
    return false
  }
  setLoading(true)
  const [e, d] = await awaitWrap(getTotal(condition))
  setLoading(false)
  if (e) {
    return message.warning(e.message)
  }
  setCasenum(d.casenum || 0)
  setDisputeamount(d.disputeamount || 0)
}

function Main () {
  const ref = useRef(null)
  const initialValues = getThisYear()
  const [condition, setCondition] = useState(null)
  const [formData, setFormData] = useState({})
  const [loading, setLoading] = useState(false)
  const [casenum, setCasenum] = useState(0)
  const [disputeamount, setDisputeamount] = useState(0)
  useEffect(() => {
    const c = ref.current
    setTimeout(() => {
      c.setFieldsValue({})
      c.submit()
    }, 0)
  }, [ref])
  useEffect(() => {
    initTotal(condition, setLoading, setCasenum, setDisputeamount)
  }, [condition])
  return (
    <div className={style.container}>
      <SearchForm ref={ref} name='finance-case-statistic' initialValues={initialValues} disableParams={['caseno', 'serieno', 'casetype', 'casesubtype', 'causeactionType']} onChange={(c, d) => formatCondition(c, d, setCondition, setFormData)} />
      <div className={style['total-line']}>
        {loading ? <span>加载中</span> : <span>案件数 {casenum} 件 / 总标的 {transferUnit(disputeamount)} </span>}
      </div>
      <div className={style['chart-container']}>
        <CaseTypeBlock condition={condition} formData={formData} />
      </div>
    </div>
  )
}

export default Main
